package com.atlin.project.controller;

import com.atlin.beaconsapicommon.model.domain.SysUser;
import com.atlin.project.annotation.AuthCheck;
import com.atlin.project.annotation.Log;
import com.atlin.project.common.BaseResponse;
import com.atlin.project.common.DeleteRequest;
import com.atlin.project.common.ErrorCode;
import com.atlin.project.common.ResultUtils;
import com.atlin.project.contant.UserConstant;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.model.dto.sysUser.*;
import com.atlin.project.model.enums.BusinessType;
import com.atlin.project.model.vo.SysUserVO;
import com.atlin.project.service.SysUserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

import static com.atlin.project.contant.UserConstant.ADMIN_ROLE;

/**
 * 用户接口
 *
 * @author atlin
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    /**
     * 用户注册
     *
     * @param sysUserRegisterRequest 注册参数
     * @return 新用户id
     */
    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody SysUserRegisterRequest sysUserRegisterRequest) {
        if (sysUserRegisterRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String userAccount = sysUserRegisterRequest.getUserAccount();
        String userPassword = sysUserRegisterRequest.getUserPassword();
        String checkPassword = sysUserRegisterRequest.getCheckPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long result = sysUserService.userRegister(userAccount, userPassword, checkPassword);
        return ResultUtils.success(result);
    }

    @PostMapping("/userAdd")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Long> userAdd(@RequestBody SysUserAddRequest sysUserAddRequest) {
        if (sysUserAddRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        long result = sysUserService.userAdd(sysUserAddRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param sysUserLoginRequest 登录参数
     * @param request             登录请求
     * @return 脱敏后的用户信息
     */
    @PostMapping("/login")
    public BaseResponse<SysUser> userLogin(@RequestBody SysUserLoginRequest sysUserLoginRequest, HttpServletRequest request) {
        if (sysUserLoginRequest == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = sysUserLoginRequest.getUserAccount();
        String userPassword = sysUserLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.userLogin(userAccount, userPassword, request);
        return ResultUtils.success(user);
    }

    /**
     * 当前登录用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/current")
    public BaseResponse<SysUserVO> getCurrentUser(HttpServletRequest request) {

        System.out.println("会话："+request.getSession().getId());
        SysUser user = sysUserService.getLoginUser(request);
        return ResultUtils.success(sysUserService.getUserVO(user));
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @Log(title = "用户")
    public BaseResponse<SysUser> getUserById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        SysUser user = sysUserService.getById(id);
        ThrowUtils.throwIf(user == null, ErrorCode.NULL_ERROR);
        return ResultUtils.success(user);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<SysUserVO> getUserVOById(long id, HttpServletRequest request) {
        BaseResponse<SysUser> response = getUserById(id, request);
        SysUser user = response.getData();
        return ResultUtils.success(sysUserService.getUserVO(user));
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = sysUserService.userLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param sysUserQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<SysUser>> listUserByPage(@RequestBody SysUserQueryRequest sysUserQueryRequest,
                                                      HttpServletRequest request) {
        long current = sysUserQueryRequest.getCurrent();
        long size = sysUserQueryRequest.getPageSize();
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<SysUser> userPage = sysUserService.page(new Page<>(current, size),
                sysUserService.getQueryWrapper(sysUserQueryRequest));
        return ResultUtils.success(userPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param sysUserQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<SysUserVO>> listUserVOByPage(@RequestBody SysUserQueryRequest sysUserQueryRequest,
                                                          HttpServletRequest request) {
        if (sysUserQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = sysUserQueryRequest.getCurrent();
        long size = sysUserQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<SysUser> userPage = sysUserService.page(new Page<>(current, size),
                sysUserService.getQueryWrapper(sysUserQueryRequest));
        Page<SysUserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
        List<SysUserVO> sysUserVO = sysUserService.getUserVO(userPage.getRecords());
        userVOPage.setRecords(sysUserVO);
        return ResultUtils.success(userVOPage);
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = ADMIN_ROLE)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = deleteRequest.getId();
        boolean b = sysUserService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 修改用户信息
     *
     * @param sysUserUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @Log(title = "用户管理",businessType = BusinessType.UPDATE)
    public BaseResponse<Boolean> updateUser(@RequestBody SysUserUpdateRequest sysUserUpdateRequest, HttpServletRequest request) {
        if (sysUserUpdateRequest == null || sysUserUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = sysUserUpdateRequest.getId();
        String userRole = sysUserUpdateRequest.getUserRole();

        SysUser loginUser = sysUserService.getLoginUser(request);

        // 仅管理员与用户自己可以修改 且 非管理员不能修改角色 管理员也不能修改本身
        if (sysUserService.isAdmin(loginUser) && id.equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "管理员账户不能修改！");
        }
        ThrowUtils.throwIf(!sysUserService.isAdmin(loginUser) && !Objects.equals(loginUser.getId(), id), ErrorCode.NO_AUTH_ERROR);
        ThrowUtils.throwIf(ADMIN_ROLE.equals(userRole), ErrorCode.NO_AUTH_ERROR);

        SysUser user = new SysUser();
        BeanUtils.copyProperties(sysUserUpdateRequest, user);

        Boolean result = sysUserService.userUpdate(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

}
